<?php

namespace App\Console\Commands;

use App\ProjectAttachment;
use App\Services\WordToPdfService;
use Exception;
use Illuminate\Console\Command;
use Log;

class ConvertAttachmentsForPreview extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'convert-attachments-for-preview';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->log('Command started');

        $convertSvc = new WordToPdfService();

        while (true) {
            $attachment = ProjectAttachment::whereIn('format', ['doc', 'docx'])
                ->where('filesize', '>', 0)
                ->whereNull('preview_filepath')
                ->where('convert_tries', '<', '3')
                ->first();
            if (empty($attachment)) {
                $this->log('No more attachment to convert');
                break;
            }
            $this->log("Attachment #{$attachment->id} fetched");

            $attachment->increment('convert_tries');

            $wordFileRealPath = public_path($attachment->filepath);
            $this->log("Word file path: $wordFileRealPath");

            if (file_exists($wordFileRealPath) && filesize($wordFileRealPath) > 0) {

                $wordFilePathinfo = pathinfo($attachment->filepath);
                $wordFileDirPath = $wordFilePathinfo['dirname'];
                $pdfFileDirPath = "$wordFileDirPath/converted";
                $pdfFileDirRealPath = public_path($pdfFileDirPath);
                if (!file_exists($pdfFileDirRealPath)) {
                    mkdir($pdfFileDirRealPath, 0777, true);
                }
                $pdfFilePath = "$pdfFileDirPath/{$wordFilePathinfo['filename']}.pdf";
                $pdfFileRealPath = public_path($pdfFilePath);

                try {
                    $this->log("Convert $wordFileRealPath to $pdfFileRealPath");
                    $success = $convertSvc->convert($wordFileRealPath, $pdfFileRealPath);
                    if ($success) {
                        $this->log("Success");
                        $attachment->update(['preview_filepath' => $pdfFilePath]);
                    } else {
                        $lastException = $convertSvc->getLastException();
                        if ($lastException instanceof Exception) {
                            throw $lastException;
                        }
                    }
                } catch (Exception $e) {
                    $attachment->update(['convert_exception' => substr((string)$e, 0, 10000)]);
                }

            } else {
                $this->log("File not found: $wordFileRealPath");
            }

//            break;

        }

        $this->log('Command finished');
    }

    private function log($msg)
    {
        $now = now();
        $pid = posix_getpid();
        $this->line("[$now][$pid]$msg");
    }
}
